package cn.leyou.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 解决跨域的配置类, 注意:***加了这个@CrossOrigin, 千万不要加这跨域配置,
 * 否则会出现The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8080, *', but only one is allowed. Origin 'http://localhost:8080' is therefore not allowed access.
 * 跨域配置重复问题,导致前台不能获得数据
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2019-8-9
 */
@Configuration
public class LeyouCorsConfiguration {

    /**
     * 配置CorsFilter的Bean的实例
     * @return CorsFilter
     */
    @Bean
    public CorsFilter corsFilter(){

        // 初始化cors的配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许跨域的域名, 如果允许携带cookie, corsConfiguration.addAllowedOrigin("http://127.0.0.1:10010");就不能写*
       //* corsConfiguration.addAllowedOrigin("http://127.0.0.1:9001");
        //1) 允许的域,不要写*，否则cookie就无法使用了
        corsConfiguration.addAllowedOrigin("*");
//        corsConfiguration.addAllowedOrigin("http://127.0.0.1:9002");
        corsConfiguration.setAllowCredentials(true);
        //3) 允许的请求方式
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.addAllowedMethod("HEAD");
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("PATCH");
        corsConfiguration.addAllowedHeader("*");

        // 实例化一个UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",corsConfiguration);

        // 返回corsFilter实例, 参数: cors配置源接口对象
        return new CorsFilter(configurationSource);
    }
}
